
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;


using Yozeev.BusinessLogic;
using Yozeev.BusinessLogic.Dtos;
using Yozeev.BusinessLogic.DomainService;
using Yozeev.BusinessLogic.Authorization;
using Yozeev.BusinessLogic.BoatBasic.ExcelDto;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Yozeev.IO.ExcelHelper;
using Yozeev.Common;
using Abp.Authorization.Users;

namespace Yozeev.BusinessLogic
{
	/// <summary>
	/// Wharf应用层服务的接口实现方法  
	///</summary>
	[AbpAuthorize]
	public class WharfAppService : YozeevAppServiceBase, IWharfAppService
    {
        private readonly IRepository<Wharf, Guid> _entityRepository;

        private readonly IWharfManager _entityManager;

		private readonly IExcelHelper _excelHelper;

		private readonly IQueryHelper _queryHelper;

		/// <summary>
		/// 构造函数 
		///</summary>
		public WharfAppService(
        IRepository<Wharf, Guid> entityRepository
        ,IWharfManager entityManager
			,IExcelHelper excelHelper
			, IQueryHelper queryHelper
        )
        {
            _entityRepository = entityRepository; 
             _entityManager=entityManager;
			_excelHelper = excelHelper;
			_queryHelper = queryHelper;
        }


        /// <summary>
        /// 获取Wharf的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[HttpPost]
        public async Task<PagedResultDto<WharfListDto>> GetPaged(GetWharfsInput input)
		{
			var expression = _queryHelper.WhereExp<Wharf>(input.queryData);
			if (AbpUserBase.AdminUserName != GetCurrentUser().UserName)
				expression = _queryHelper.SetWhereExp<Wharf>(expression, GetViewTypeEnum<Wharf>(), await GetBranchUser());
			var query = _entityRepository.GetAll().Where(expression);
			// TODO:根据传入的参数添加过滤条件


			var count = await query.CountAsync();

			var entityList = await query
					.OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

			// var entityListDtos = ObjectMapper.Map<List<WharfListDto>>(entityList);
			var entityListDtos =entityList.MapTo<List<WharfListDto>>();

			return new PagedResultDto<WharfListDto>(count,entityListDtos);
		}


		/// <summary>
		/// 通过指定id获取WharfListDto信息
		/// </summary>
		public async Task<WharfListDto> GetById(EntityDto<Guid> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<WharfListDto>();
		}

		/// <summary>
		/// 获取编辑 Wharf
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task<GetWharfForEditOutput> GetForEdit(NullableIdDto<Guid> input)
		{
			var output = new GetWharfForEditOutput();
WharfEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<WharfEditDto>();

				//WharfEditDto = ObjectMapper.Map<List<WharfEditDto>>(entity);
			}
			else
			{
				editDto = new WharfEditDto();
			}

			output.Wharf = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改Wharf的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task CreateOrUpdate(CreateOrUpdateWharfInput input)
		{

			if (input.Wharf.Id.HasValue)
			{
				await Update(input.Wharf);
			}
			else
			{
				await Create(input.Wharf);
			}
		}


		/// <summary>
		/// 新增Wharf
		/// </summary>
		protected virtual async Task<WharfEditDto> Create(WharfEditDto input)
		{
			//TODO:新增前的逻辑判断，是否允许新增

            // var entity = ObjectMapper.Map <Wharf>(input);
            var entity=input.MapTo<Wharf>();
			

			entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<WharfEditDto>();
		}

		/// <summary>
		/// 编辑Wharf
		/// </summary>
		protected virtual async Task Update(WharfEditDto input)
		{
			//TODO:更新前的逻辑判断，是否允许更新

			var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);

			// ObjectMapper.Map(input, entity);
		    await _entityRepository.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除Wharf信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task Delete(EntityDto<Guid> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除Wharf的方法
		/// </summary>
		public async Task BatchDelete(List<Guid> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}


		/// <summary>
		/// 导出Wharf为excel表,等待开发。
		/// </summary>
		/// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}


		/// <summary>
		/// 从Excel表导入数据
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		public async Task<ExcelResultDto> ImportWharf(IFormFile file)
		{
			string errorMessage = "";
			bool result;
			try
			{
				List<WharfExcelDto> data = _excelHelper.ReadToList<WharfExcelDto>(file);
				var wharfs = new List<Wharf>();
				foreach (var dto in data)
				{
					wharfs.Add(new Wharf
					{
						WharfName=dto.WharfName,
						WharfLeader=dto.WharfLeader,
						LeaderMobile = dto.LeaderMobile,
						WharfPosition=dto.WharfPosition,
						IsEenable=false,
						CreationTime = DateTime.Now,
						CreatorUserId = AbpSession.UserId,
						Id = Guid.NewGuid(),
					});
				}
				result = await _entityManager.WharfInsertAsync(wharfs);
			}
			catch (Exception e)
			{
				result = false;
				errorMessage = e.Message;
			}
			return new ExcelResultDto { Result = result, ErrorMessage = errorMessage };
		}
	}
}


